const mongoose = require('mongoose');
const jwt = require("jsonwebtoken");

const { md5, secretKey } = require("../utils/salt")

const reg = async ({ userName, userPassword }) => {
    const data = {
        userName,
        userPassword: md5(userPassword)
    }
    return await mongoose.model('users').create(data);
}

const checkName = async ({ userName }) =>
    await mongoose.model('users').findOne({ userName });

const login = async ({ userName, userPassword }) => {
    const data = await mongoose.model('users').findOne({ userName, userPassword: md5(userPassword) })
    // if (data) {
    //     const payload = {
    //         username,
    //     };
    //     let token = jwt.sign(
    //         payload,
    //         secretKey,
    //         {
    //             expiresIn: 60 * 60 * 2400// 秒
    //         }
    //     );
    //     return {
    //         state: true,
    //         token
    //     }
    // } else {
    //     return {
    //         state: false
    //     }
    // }
    return data
}


const getList = async ({ curPage, eachPage }) => {
    const result = {
        curPage: ~~curPage,
        eachPage: ~~eachPage,
        total: 0,
        maxPage: 0,
        rows: [],
    }
    const adminstModel = mongoose.model('users');
    result.maxPage = Math.ceil(result.total / result.eachPage);
    result.total = await adminstModel.countDocuments();

    result.rows = await adminstModel.find()
        .skip((result.curPage - 1) * result.eachPage)
        .limit(result.eachPage)
        .exec();

    return result
}

module.exports = { reg, checkName, login, getList }